; (function (window, $) {
  // dict
  var dict = {
    feature: [
      '无需担保',
      '放款速度快',
      '手续简便',
      '利率低',
      '手续费低',
      '额度高'
    ],
    payment: ['等额本金', '等额本息', '先息后本', '一次性还本付息'],
    takeTimes: [
      '一天以内',
      '三天以内',
      '五天以内',
      '一周以内',
      '半月以内',
      '一月以内',
      '三月以内'
    ],
    professional: ['自由职业者', '个体户', '企业主', '上班族'],
    mortgage: ['信用', '车押', '房押', '质押']
  }

  $(function () {
    util.needChannelLogin(true)

    // your should full your info first

    util.ajax({
      url: '/user/manager',
      success: function (res) {
        if (parseInt(res.data.auditStatus) === 0) {
          layer.alert(
            '请前往:"我的资料" 完善您的信息，并且在资料认证成功后才可以发布产品',
            {
              skin: 'demo-class',
              closeBtn: 0
            },
            function (index) {
              window.location.href = '/channel/myprofile.html'
            }
          )
          // layer end
        }
      }
    })

    // get inst
    // getInst(0)

    //close dialog
    /*
        $("#addPro-close").on('click',function(){
            $('#addPro').hide();
        });*/

    //uploadbtn
    $('input[type="file"]').on('change', function () {
      var fileInput = $(this)

      util.fileUpload(fileInput[0].files[0], function (res) {
        fileInput.prev('span').text('点击重新上传')
        fileInput.next('input[type="hidden"]').val(res.data)
      })
    })

    $('.uploadbtn').hover(
      function () {
        var imgUrl = $(this)
          .find("input[type='hidden']")
          .val()
        console.log(imgUrl)
        if (imgUrl !== '') {
          $(this)
            .find('img')
            .attr('src', imgUrl)
          $(this)
            .find('a')
            .attr('href', imgUrl)
            .show()
        }
      },
      function () {
        $(this)
          .find('a')
          .hide()
      }
    )

    $('input[type="file"]').on('click', function () {
      if (parseInt($("select[name='instType']").val()) === 0) {
        event.stopPropagation()
        layer.alert('抱歉，暂不能自定义银行产品logo', {
          skin: 'demo-class',
          closeBtn: 0
        })
        // alert('抱歉，暂不能自定义银行产品logo')
        return false
      }
    })

    $("select[name='instType']").on('change', function () {
      getInst($(this).val())
    })

    //number
    $('input.number').on('keyup', function () {
      var val = $(this).val()
      var exp = new RegExp(/^[0-9]{0,}\.?[0-9]{0,4}$/g)
      if (val.match(exp) === null) {
        $(this).val($(this).data('old'))
      } else {
        $(this).data('old', val)
        if (val.substr(0, 1) == '.') {
          $(this).val('0' + val)
        }
      }
    })

    //int
    $('input.int').on('keyup', function () {
      var val = $(this).val()
      $(this).val(val.replace(/[^0-9]/g, ''))
    })

    //select2
    $('#shrq').select2({
      placeholder: '适合人群',
      language: 'zh-CN'
    })

    $('#cpbq').select2({
      placeholder: '产品特点',
      language: 'zh-CN'
    })

    $('#hkfs').select2({
      placeholder: '还款方式',
      language: 'zh-CN'
    })

    $('#jgmc').select2({
      placeholder: '机构名称',
      language: 'zh-CN',
      tags: 'true'
    })

    $('#jgmc').on('change', function () {
      $(".uploadbtn input[name='logo']").val(
        $(this)
          .find('option:checked')
          .data('logo')
      )
    })

    $('a.addfinalbtn').on('click', function () {
      var formobj = {}
      var vali = true

      // get all text
      $('input[type="text"].formobj').each(function () {
        if (!vali) {
          return
        }

        if ($(this).val() === '') {
          layer.alert($(this).data('label') + ' 未填写', {
            skin: 'demo-class',
            closeBtn: 0
          })
          // alert($(this).data('label') + ' 未填写')
          vali = false
        }
        var key = $(this).attr('name')
        var val = $(this).val()
        formobj[key] = val
      })

      // get all select
      $('select.formobj').each(function () {
        // don't check instId
        if (!vali || $(this).attr('name') == 'instId') {
          return
        }

        if (parseInt($(this).val()) === -1 || $(this).val() === null) {
          console.log('-1 or null', $(this).attr('name'))
          layer.alert($(this).data('label') + ' 未选择', {
            skin: 'demo-class',
            closeBtn: 0
          })
          // alert($(this).data('label') + ' 未选择')
          vali = false
        }
        var key = $(this).attr('name')
        var val = $(this).val()
        formobj[key] = val
      })

      //get all hidden
      $('input[type="hidden"].formobj').each(function () {
        if (!vali) {
          return
        }

        if ($(this).val() === '') {
          layer.alert('未上传logo', {
            skin: 'demo-class',
            closeBtn: 0
          })
          // alert('未上传logo')
          vali = false
        }
        var key = $(this).attr('name')
        var val = $(this).val()
        formobj[key] = val
      })

      // get all textarea
      $('textarea.formobj').each(function () {
        if (!vali) {
          return
        }

        if ($(this).val() === '') {
          layer.alert($(this).data('label') + ' 未填写', {
            skin: 'demo-class',
            closeBtn: 0
          })
          // alert($(this).data('label') + ' 未填写')
          vali = false
        }
        var key = $(this).attr('name')
        var val = $(this).val()
        formobj[key] = val
      })

      if (!vali) {
        return
      }

      // text
      formobj.featuresText = []
      formobj.paymentText = []
      formobj.professionalText = []


      for (var i = 0; i < formobj.features.length; i++) {
        formobj.featuresText.push(dict.feature[formobj.features[i]])
      }

      for (var j = 0; j < formobj.payment.length; j++) {
        formobj.paymentText.push(dict.payment[formobj.payment[j]])
      }

      for (var j = 0; j < formobj.professional.length; j++) {
        formobj.professionalText.push(
          dict.professional[formobj.professional[j]]
        )
      }


      // text

      // formobj.takeTimesText=dict.takeTimes[formobj.takeTimes];

      // let's check instid
      // if isNaN === true ,it will be a string
      if (isNaN($("select[name='instId']").val())) {
        if (parseInt(formobj.instType) === 0) {
          layer.alert('暂不能自定义银行机构', {
            skin: 'demo-class',
            closeBtn: 0
          })
          // alert('暂不能自定义银行机构')
          return
        } else {
          formobj.instName = $("select[name='instId']").val()
        }
      } else {
        formobj.instId = $("select[name='instId']").val()
        formobj.instName = $("select[name='instId'] option:checked").text()
      }

      //convert array to string

      for (var gg in formobj) {
        if (formobj[gg] instanceof Array) {
          formobj[gg] = formobj[gg].join(',')
        }
      }

      //big small 
      if (parseInt($("input[name='rateMax']").val()) < parseInt($("input[name='rateMin']").val())) {
        layer.alert('最小贷款利率不能大于最大贷款利率', {
          skin: 'demo-class',
          closeBtn: 0
        });
        return;
      }

      if (parseInt($("input[name='loanTimeMax']").val()) < parseInt($("input[name='loanTimeMin']").val())) {
        layer.alert('最小贷款期限不能大于最大贷款期限', {
          skin: 'demo-class',
          closeBtn: 0
        });
        return;
      }

      if (parseInt($("input[name='loanMax']").val()) < parseInt($("input[name='loanMin']").val())) {
        layer.alert('最小贷款额度不能大于最大贷款额度', {
          skin: 'demo-class',
          closeBtn: 0
        });
        return;
      }

      //faker data
      // formobj.productId=0;
      formobj.credit = 0
      formobj.remark = 'afosudfh'

      console.log('before send', formobj)

      util.ajax({
        url: '/manager/product/add',
        type: 'POST',
        data: formobj,
        success: function (res) {
          $('#addPro').show()
        }
      })
    })
  })

  function getInst(id) {
    $.ajax({
      url: util.host + '/common/institution/getInstitutionList?type=' + id + '&limit=100',
      type: 'POST',
      success: function (res) {
        console.log(res)
        var arr = res.data.rows
        var arr_length = arr.length
        var html = ''
        for (var i = 0; i < arr_length; i++) {
          html +=
            '<option value="' +
            arr[i].id +
            '" data-logo="' +
            arr[i].logo +
            '">' +
            arr[i].name +
            '</option>'
        }

        $('select[name="instId"]').html(html)
        $(".uploadbtn input[name='logo']").val(
          $('#jgmc')
            .find('option')
            .eq(0)
            .data('logo')
        )
      }
    })
  }
})(window, jQuery)
